package com.miplus.ccrm.core.service.aicall;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.*;
import com.miplus.ccrm.core.controller.vo.aicall.*;
import com.miplus.ccrm.core.controller.vo.ficase.ImpResultVo;
import com.miplus.ccrm.core.controller.vo.strategy.PreViewTrigReqVo;
import com.miplus.ccrm.core.mapper.*;
import com.miplus.ccrm.core.pojo.*;
import com.miplus.ccrm.core.service.ExportService;
import com.miplus.ccrm.core.service.JRbtLinker;
//import com.miplus.ccrm.core.service.collect.FiCreditcasesService;
//import com.miplus.ccrm.core.service.collect.FiImportHistService;
import com.miplus.ccrm.core.service.aiqm.TRecorderService;
import com.miplus.ccrm.core.service.crd.FiCreditcasesService;
import com.miplus.ccrm.core.service.crd.FiImportHistService;
import com.miplus.ccrm.core.service.crd.FiTaskService;
import com.miplus.ccrm.core.service.sto.PlAi94CallbackmsgService;
import com.miplus.ccrm.core.service.sto.PlAi94ChatService;
import com.miplus.ccrm.sms.aicall.AiCallAESUtil;
import com.miplus.ccrm.sms.aicall.AiCallService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
* @author pc
* @description 针对表【OB_CALL_CASE(AI外呼表)】的数据库操作Service实现
* @createDate 2024-10-30 17:53:19
*/
@Service
@Slf4j
public class ObCallCaseServiceImpl extends MPJBaseServiceImpl<ObCallCaseMapper, ObCallCase>
    implements ObCallCaseService{

    @Resource
    private FiImportHistService fiImportHistService;
    @Resource
    private CpCalllistTriggerMapper triggerMapper;
    @Resource
    private FiCreditcasesService caseService;
    @Resource
    private ExportService exportService;
    @Resource
    private CpCalllistMapper cpCalllistMapper;
    @Resource
    private JRbtLinker rbtLinker;
    @Resource
    private ObJobStatusMapper obJobStatusMapper;
    @Resource
    private AiCallService aiCallService;

    @Resource
    private FiTaskService fiTaskService;
    @Resource
    private PlAi94CallbackmsgService plAi94CallbackmsgService;

    @Resource
    private PlAi94ChatService plAi94ChatService;

    @Resource
    private TRecorderService recorderService;
    @Override
    public IPage<ObCallListResVo> dialList(ObCallListReqVo paras)
    {
        return selectJoinListPage(new Page<>(paras.getPageNum(), paras.getPageSize()),
                ObCallListResVo.class,
                new MPJLambdaWrapper<ObCallCase>()
                        .leftJoin(FiCreditcases.class, "fi",FiCreditcases::getCreditcaseid, ObCallCase::getFicaseid)
                        .leftJoin(ConCustomer.class, ConCustomer::getCustomernumber, ObCallCase::getPdCustomerid)
                        .selectAs(ObCallCase::getCaseid,ObCallListResVo::getDataid)
                        .selectAs(ObCallCase::getPdJobid,ObCallListResVo::getClid)
                        .selectAs(ObCallCase::getFicaseid,ObCallListResVo::getFicaseid)
                        .selectAs(ConCustomer::getCustname,ObCallListResVo::getCustname)
                        .selectAs(FiCreditcases::getOverdueTotalamt,ObCallListResVo::getOdudprin)
                        .selectAs(FiCreditcases::getMthsDay,ObCallListResVo::getMthsday)
                        .selectAs(FiCreditcases::getRepayDays,ObCallListResVo::getRepayday)
                        .selectAs(FiCreditcases::getCcc,ObCallListResVo::getCcc)
                        .selectAs(ObCallCase::getDialdt,ObCallListResVo::getDialdt)
                        .selectAs(ObCallCase::getPdDialcnt, ObCallListResVo::getDialcnt)
                        .selectAs("fun_getnames('COLLECT.QUEUE',fi.ccc)", ObCallListResVo::getCccdsc)
                        .selectAs("fun_getnames('CAMPAIGN.CB.STATUS',t.pd_curstatus)", ObCallListResVo::getPdstatusdsc)
                        .selectAs("(select cp.name from cp_calllist cp where cp.clid=t.pd_jobid)", ObCallListResVo::getClidname)
                        .selectAs("(select g.helpstr from cp_strategy g where g.ccc=t.pd_ccc and g.clid=t.pd_jobid)", ObCallListResVo::getCccdsc)
                        .select(ObCallCase::getCrdt,ObCallCase::getPhone,ObCallCase::getBatchid,ObCallCase::getPdCurstatus)
                        .eq(JPubUtils.IsNotEmpty(paras.getBatchid()), ObCallCase::getBatchid, paras.getBatchid())
                        .eq(JPubUtils.IsNotEmpty(paras.getClid()), ObCallCase::getPdJobid, paras.getClid())
                        .eq(JPubUtils.IsNotEmpty(paras.getPdstatus()), ObCallCase::getPdCurstatus, paras.getPdstatus())
                        .eq(JPubUtils.IsNotEmpty(paras.getFicaseid()), ObCallCase::getAccountid, paras.getFicaseid())
                        .eq(JPubUtils.IsNotEmpty(paras.getPhone()), ObCallCase::getPhone, paras.getPhone())
                        .between(JPubUtils.IsNotEmpty(paras.getStartdt()), ObCallCase::getCrdt, JPubUtils.StringToDate(paras.getStartdt()), JPubUtils.StringToDate(paras.getEnddt()))
                        .eq(JPubUtils.IsNotEmpty(paras.getCcc()), ObCallCase::getPdCcc, paras.getCcc())
                        .between(JPubUtils.IsNotEmpty(paras.getCallstartdt()), ObCallCase::getDialdt, JPubUtils.StringToDate(paras.getCallstartdt()), JPubUtils.StringToDate(paras.getCallenddt()))
                        .orderByDesc(ObCallCase::getDialdt)
        );
    }

    @Override
    public CmdResVo updateDataStatus(UpDataStatusReqVo statusReqVo)
    {
        int ret=0;
        if(JPubUtils.IsEqual(statusReqVo.getStatus(),"1")) {
            ret=baseMapper.update(null,
                    new UpdateWrapper<ObCallCase>()
                            .lambda()
                            .eq(ObCallCase::getBatchid, statusReqVo.getBatchid())
                            .eq(ObCallCase::getPdCurstatus,"N")
                            .set(ObCallCase::getPdCurstatus,"O")
                            .set(ObCallCase::getPdStatus,"O")
            );
        }else{
            ret=baseMapper.update(null,
                    new UpdateWrapper<ObCallCase>()
                            .lambda()
                            .eq(ObCallCase::getBatchid, statusReqVo.getBatchid())
                            .eq(ObCallCase::getPdCurstatus,"O")
                            .set(ObCallCase::getPdCurstatus,"N")
                            .set(ObCallCase::getPdStatus,"N")
            );
        }

        FiImportHist hist=new FiImportHist();
        hist.setStatus(JPubUtils.StringToInt(statusReqVo.getStatus()));
        hist.setBatchid(statusReqVo.getBatchid());
        fiImportHistService.updateById(hist);

        return new CmdResVo(ret,statusReqVo.getBatchid());
    }

    @Override
    public CmdResVo updateCallStatus(UpCallStatusVo callStatusVo)
    {
        int ret=baseMapper.update(null,new UpdateWrapper<ObCallCase>()
                .lambda()
                .eq(ObCallCase::getCaseid,callStatusVo.getCaseid())
                .set(ObCallCase::getPdStatus,callStatusVo.getNewstatus())
                .set(ObCallCase::getPdCurstatus,callStatusVo.getNewstatus())
                .set(ObCallCase::getPdResult,0)
                .set(ObCallCase::getPdComplete,"0")
                .set(ObCallCase::getPdDt2d,null)
        );
        return new CmdResVo(ret,callStatusVo.getCaseid());
    }

    private MPJLambdaWrapper getQueryWrapper(Integer triggerid)
    {
//        String noinctags="";
//        CpCalllistTrigger trigger=triggerMapper.selectById(triggerid);
//        String tags= JPubUtils.getInString(trigger.getCusttags());
//        if(JPubUtils.IsNotEmpty(tags)){
//            noinctags = JPubUtils.BoolToString(trigger.getNoinctag());
//        }
//        return new MPJLambdaWrapper<FiCreditcases>()
//                .innerJoin(ConCustomer.class, "cu", ConCustomer::getCustomernumber, FiCreditcases::getCustomernumber)
//                .ge(JPubUtils.IsNotEmpty(trigger.getMthsodue()), FiCreditcases::getMthsOdue, trigger.getMthsodue())
//                .le(JPubUtils.IsNotEmpty(trigger.getMthsodue2()), FiCreditcases::getMthsOdue, trigger.getMthsodue2())
//                .ge(JPubUtils.IsNotEmpty(trigger.getOverday1()), FiCreditcases::getMthsDay, trigger.getOverday1())
//                .le(JPubUtils.IsNotEmpty(trigger.getOverday2()), FiCreditcases::getMthsDay, trigger.getOverday2())
//                .isNotNull(ConCustomer::getCustphone)
//                .apply(JPubUtils.IsEqual(noinctags, 0),String.format("cu.customernumber in (select tag.custid from con_customertag tag where tag.custid=t.customernumber and tag.id in ('%s'))", tags))
//                .apply(JPubUtils.IsEqual(noinctags, 1), String.format("cu.customernumber not in (select tag.custid from con_customertag tag where tag.custid=t.customernumber and tag.id in ('%s'))", tags));
        return null;
    }

    @Override
    public IPage<ImpObCaseResVo> preViewQmData(String triggerid, Integer pagenum, Integer pagesize)
    {
//        Integer trint=Integer.parseInt(triggerid);
//        MPJLambdaWrapper<FiCreditcases> quyWrapper=getQueryWrapper(trint);
//        return caseService.selectJoinListPage(new Page<>(pagenum, pagesize),
//                ImpObCaseResVo.class,
//                quyWrapper.selectAs(FiCreditcases::getCreditcaseid, ImpObCaseResVo::getFicaseid)
//                        .selectAs(ConCustomer::getCustphone, ImpObCaseResVo::getPhone)
//                        .selectAs(FiCreditcases::getCustomernumber,ImpObCaseResVo::getCustomerid)
//                        .selectAs(FiCreditcases::getCreditAcct, ImpObCaseResVo::getAccountid)
//                        .select(FiCreditcases::getOdudPrin,FiCreditcases::getMthsDay,FiCreditcases::getRepayday)
//                        .select(ConCustomer::getCustomernumber, ConCustomer::getCustname)
//        );

        return null;
    }

    @Override
    public IPage<ImpObCaseResVo> quyImpObHist(PreViewTrigReqVo paras)
    {
        CpCalllist calllist=cpCalllistMapper.selectById(paras.getClid());
        String triggerid=calllist.getTriggerid();
        if(JPubUtils.IsEmpty(triggerid)){
            throw new ServiceException(EnumRCode.NoFindConfig.value, EnumRCode.NoFindConfig.name);
        }
        return preViewQmData(triggerid,1,JPubUtils.exportMaxCount);
    }

    private List<ImpObCaseResVo> buildImpData(String triggerid)
    {
        IPage<ImpObCaseResVo> pages=preViewQmData(triggerid,1,JPubUtils.exportMaxCount);
        return pages.getRecords();
    }

    private List<ImpObCaseResVo> buildImpData(List<ImpObItemVo> list)
    {
        List<ImpObCaseResVo> pagelist=new ArrayList<>();
        for(ImpObItemVo resVo : list){
            ImpObCaseResVo p=new ImpObCaseResVo();
            p.setPhone(resVo.getPhone());
            p.setCustname(resVo.getCustname());
            p.setCustomerid(resVo.getCustomerid());
            p.setAccountid(resVo.getAccountid());
            p.setMthsday(resVo.getMthsday());
            p.setOdudprin(resVo.getOdudprin());
            p.setRepayday(resVo.getRepayday());
            pagelist.add(p);
        }

        return pagelist;
    }

    @Override
    public ImpResultVo impObCase(String $usrid, ImpObCallReqVo paras)
    {
        ImpResultVo resultVo=null;
        String imptype=paras.getImptype();
        if(JPubUtils.IsEqual(imptype,"file")) {
            List<ImpObCaseResVo> list=buildImpData(paras.getAddVoList());
            resultVo=impObCase($usrid,paras.getClid(),"",paras.getBatchdsc(),imptype,list);
        }else{
            CpCalllist calllist=cpCalllistMapper.selectById(paras.getClid());
            String triggerid=calllist.getTriggerid();
            if(JPubUtils.IsEmpty(triggerid)){
                throw new ServiceException(EnumRCode.NoFindConfig.value, EnumRCode.NoFindConfig.name);
            }
            resultVo=impObCase($usrid,calllist.getClid(),triggerid,paras.getBatchdsc(),imptype);
        }
        return resultVo;
    }

    @Override
    public ImpResultVo impObCase(String $usrid,String clid,String triggerid,String batchdsc,String imptype)
    {
        List<ImpObCaseResVo> list=buildImpData(triggerid);
        return impObCase($usrid,clid,triggerid,batchdsc,imptype,list);
    }


    public ImpResultVo impObCase(String $usrid,String clid,String triggerid,String batchdsc,
                                 String imptype,List<ImpObCaseResVo> list)
    {
//        int okcnt=0;
//        SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmssSSS");
//        String batchid='D'+df.format(new Date());
//        //先写一个后面在update，目的是为了写入数据异常，可以delete掉
//        fiImportHistService.AddImportHist(batchid,
//                batchdsc,
//                $usrid,
//                0,
//                "dialtemplate",
//                triggerid,
//                list.size(),
//                okcnt,
//                clid,
//                imptype
//        );
//        log.info("impObCase:Records={}",list.size());
//        List<ObCallCase> dataList=new ArrayList<>();
//        for(ImpObCaseResVo p : list){
//            ObCallCase obcase=new ObCallCase();
//            obcase.setPriority("10");
//            obcase.setBatchid(batchid);
//            obcase.setPdStatus("N");
//            obcase.setPdCurstatus("N");
//            obcase.setPdJobid(clid);
//            obcase.setCrdt(new Date());
//            obcase.setPhone(p.getPhone());
//            obcase.setAccountid(p.getAccountid());
//            obcase.setPdCustomerid(p.getCustomerid());
//            obcase.setUf1(p.getCustname());
//            if(JPubUtils.IsNotEmpty(p.getFicaseid())){
//                obcase.setFicaseid(p.getFicaseid());
//            }
//            if(p.getOdudprin()==null){
//                obcase.setUf2("0");
//            }else {
//                obcase.setUf2(p.getOdudprin().toString());
//            }
//            if(p.getMthsday()==null){
//                obcase.setUf3("0");
//            }else {
//                obcase.setUf3(p.getMthsday().toString());
//            }
//            obcase.setUf4(p.getRepayday());
//            dataList.add(obcase);
//            okcnt++;
//        }
//        saveBatch(dataList);
//
//        fiImportHistService.UpImportHist(batchid,okcnt);
//        list.clear();
//
//        ImpResultVo resultVo=new ImpResultVo();
//        resultVo.setBatchid(batchid);
//        resultVo.setOkcnt(okcnt);
//        resultVo.setFailcnt(0);
//
//        return resultVo;
        return null;
    }

    @Override
    public IPage<TotalRepResVo> repJobTotal(TotalRepReqVo paras)
    {
        return baseMapper.quyJobTotalReport(new Page<>(paras.getPageNum(), paras.getPageSize()),
                paras.getClid(),paras.getReporttype(),
                paras.getStartdate(),paras.getEnddate()
        );
    }

    @Override
    public IPage<BatchRepResVo> repJobBatch(BatchRepReqVo paras)
    {
        return baseMapper.quyJobBatchReport(new Page<>(paras.getPageNum(), paras.getPageSize()),
                paras.getClid(),paras.getBatchid()
        );
    }

    @Override
    public CmdResVo expJobTotal(JSysUser user, TotalRepReqVo paras, HttpServletResponse response)
    {
        String $usrid = user.getUsrid();
        int pagesize = paras.getPageSize();
        if (pagesize > JPubUtils.exportMaxCount) {
            paras.setPageSize(JPubUtils.exportMaxCount);
        }
        log.info("expJobTotal:pagesize={}",pagesize);

        IPage<TotalRepResVo> pages=repJobTotal(paras);
        ArrayList arr=new ArrayList();

        String exptempid=JPubUtils.getExpTempID(paras.getExpfilename(),"外呼任务统计表");
        String filename=JPubUtils.getExpFileName(
                paras.getExpfilename(),exptempid
        );
        pages.convert(u->{
            HashMap map=JPubUtils.toExportMap(u);
            if(map!=null) arr.add(map);
            return u;
        });
        CmdResVo resVo=exportService.ToExcel(
                response,
                arr,
                paras.getExpidlist(),
                paras.getExpnamelist(),
                filename,
                $usrid
        );

        int okcount=resVo.getCount();
        if(okcount>0){
            fiImportHistService.AddExportHist(
                    resVo.getKeyId(),
                    $usrid,
                    exptempid,
                    filename,
                    okcount
            );
        }
        arr.clear();

        return resVo;
    }

    @Override
    public CmdResVo expJobBatch(JSysUser user, BatchRepReqVo paras, HttpServletResponse response)
    {
        String $usrid = user.getUsrid();
        int pagesize = paras.getPageSize();
        if (pagesize > JPubUtils.exportMaxCount) {
            paras.setPageSize(JPubUtils.exportMaxCount);
        }
        log.info("expJobBatch:pagesize={}",pagesize);

        IPage<BatchRepResVo> pages=repJobBatch(paras);
        ArrayList arr=new ArrayList();

        String exptempid=JPubUtils.getExpTempID(paras.getExpfilename(),"外呼批次统计表");
        String filename=JPubUtils.getExpFileName(
                paras.getExpfilename(),exptempid
        );
        pages.convert(u->{
            HashMap map=JPubUtils.toExportMap(u);
            if(map!=null) arr.add(map);
            return u;
        });
        CmdResVo resVo=exportService.ToExcel(
                response,
                arr,
                paras.getExpidlist(),
                paras.getExpnamelist(),
                filename,
                $usrid
        );

        int okcount=resVo.getCount();
        if(okcount>0){
            fiImportHistService.AddExportHist(
                    resVo.getKeyId(),
                    $usrid,
                    exptempid,
                    filename,
                    okcount
            );
        }
        arr.clear();

        return resVo;
    }

    @Override
    public CmdResVo dialAdmin(DialAdminCmdVo cmdVo)
    {//{jobid:aidial,cmd:start}
        String cmd= JSONObject.toJSONString(cmdVo.getData());
        int iret = rbtLinker.SendDialerCmd(cmd);
        return new CmdResVo(iret,cmdVo.getJobid());
    }

    @Override
    public CmdResVo getDialJobStatus(String jobid)
    {
        ObJobStatus jobStatus=obJobStatusMapper.selectById(jobid);
        Integer status=0;
        if(jobStatus==null){
            log.warn("getDialJobStatus.Nofind:",jobid);
        }
        else{
            status=jobStatus.getStatus();
        }
        return new CmdResVo(status,jobid);
    }
    @Override
    public ObCallCase getObCallCaseDetail(Long caseId)
    {
        return getById(caseId);
    }

    @Override
    public Ai94ResVo aiCallResult(String bodyval, String timestamp) {
        String body = JSONObject.parseObject(bodyval).get("body").toString();
        String bodyData = JSONObject.parseObject(body).get("data").toString();
        String uuid = JSONObject.parseObject(body).get("uuid").toString();
        timestamp = JSONObject.parseObject(body).get("timestamp").toString();
        String appKey = JSONObject.parseObject(body).get("appKey").toString();

        log.info("aiCallResult({}):{}",timestamp,bodyData);
        String iv= AiCallAESUtil.genTimestampIV(timestamp);
        CmdResVo resVo=aiCallService.getDecryptValue(bodyData,iv,appKey);
        if(!JPubUtils.IsEqual(resVo.getCount(),EnumRCode.Success.value)){
            throw new ServiceException(EnumRCode.ApiCryErr.value, EnumRCode.ApiCryErr.name);
        }

        JSONObject resp = JSONObject.parseObject(resVo.getKeyId());
        String caseid=resp.getString("tag"); //caseid

        if(JPubUtils.IsEmpty(caseid)){
            throw new ServiceException(EnumRCode.ArgErr.value, EnumRCode.ArgErr.name);
        }

        log.info("caseid:{},resp:{}",caseid,resp);

        String callid=resp.getString("callId");


        PlAi94Callbackmsg plAi94Callbackmsg = to9AI(new Date(), uuid, resp);

        log.info("plAi94Callbackmsg:{}",plAi94Callbackmsg);

        if("1".equals(plAi94Callbackmsg.getIsndcs())){
            return new Ai94ResVo("200","ok");
        }

        Integer statusCode=resp.getInteger("statusCode");
        String callBeginTime=resp.getString("callBeginTime");
        Integer ringTime=resp.getInteger("ringTime");
        String answerTime=resp.getString("answerTime");
        String hangupTime=resp.getString("hangupTime");
        Integer speakingDuration=resp.getInteger("speakingDuration"); //AI通话时长
        if(speakingDuration==null) speakingDuration=0;
        String individualTag=resp.getString("individualTag"); //个性标签
        String intentTag=resp.getString("intentTag"); //意向标签
//        String intentDescription=resp.getString("intentDescription"); //意向说明
//        if(JPubUtils.IsNotEmpty(intentDescription)&&intentDescription.length()>50){
//            intentDescription=intentDescription.substring(0,49);
//        }
        String chatRecord=resp.getString("chatRecord"); //对话录音，URL，可以为空
//        JSONArray chatlist=resp.getJSONArray("chats");//对话记录
        String phone=resp.getString("number");

        String ccc=toPdCCC(statusCode);

        String pdstatus="F";
        if(statusCode==1&&JPubUtils.IsNotEmpty(intentTag))
            pdstatus="R";

        int ret=baseMapper.update(null,new UpdateWrapper<ObCallCase>()
                .lambda()
                .eq(ObCallCase::getCaseid,plAi94Callbackmsg.getUf1())
                .set(ObCallCase::getPdStatus,pdstatus)
                .set(ObCallCase::getPdCurstatus,pdstatus)
                .set(ObCallCase::getPdStartdt,callBeginTime)
                .set(ObCallCase::getPdConnectdt,answerTime)
                .set(ObCallCase::getPdReleasedt,hangupTime)
                .set(ObCallCase::getPdDropdt,hangupTime)
                .set(ObCallCase::getDialspan,ringTime/1000.0)
                .set(ObCallCase::getConnectspan,speakingDuration)
                .set(ObCallCase::getQueuespan,0.0)
                .set(ObCallCase::getDialdt,JPubUtils.StringToDate(callBeginTime))
                .set(ObCallCase::getPdCcc,ccc)
//                .set(ObCallCase::getUf14,intentTag)
//                .set(ObCallCase::getUf15,intentDescription)
                .set(ObCallCase::getPdPhnnum,phone)
                .set(ObCallCase::getPdCaseid,callid)
                .setSql("PD_DIALCNT=Nvl(PD_DIALCNT,0)+1")
        );
//        baseMapper.updateToHist(caseid);

        /**
        // 逻辑待补充
        if(statusCode==1&&JPubUtils.IsNotEmpty(chatRecord)){
            TRecorder recorder=new TRecorder();
            recorder.setRecorderid(callid);
            recorder.setCallid(callid);
            recorder.setTeldnis(phone);
            recorder.setAvailable("1");
            recorder.setAgentid("aicall");
            recorder.setCalltype("OUT");
            recorder.setChannelno(-1);
            recorder.setStarttime(JPubUtils.StringToDate(callBeginTime));
            recorder.setStartdate(JPubUtils.StringToDate(callBeginTime));
            recorder.setSpendtime(new BigDecimal(speakingDuration));
//            String ipaddr="127.0.0.1";
//            if(JPubUtils.IsNotEmpty(aiCallService.aicallRecSaveAddr)){
//                ipaddr=aiCallService.aicallRecSaveAddr;
//            }
//            recorder.setRecorderip(ipaddr);
            String recfile=getUrlFileName(chatRecord);
            String recpath=chatRecord.replace(recfile,"");
            recorder.setFilename(recfile);
            recorder.setFilepath(recpath);
            recorderService.saveOrUpdate(recorder);
        }**/

        //修改催记信息  还款意愿(意向说明（intentDescription）)、结果(外呼状态描述（statusDescription）)、录音(对话录音（chatRecord）)、催记状态
        fiTaskService.lambdaUpdate()
                .eq(FiTask::getTasknumber,plAi94Callbackmsg.getUf2())
                .set(FiTask::getPtpstatus,"94-"+intentTag)// 还款意愿
                .set(FiTask::getStatus,pdstatus)
                .set(FiTask::getCticallid,callid)
                .set(FiTask::getResult,statusCode)
                .set(FiTask::getDodt,JPubUtils.StringToDate(callBeginTime))
                .set(FiTask::getDousr,"system")
                .set(FiTask::getMddt,new Date())
                .set(FiTask::getMdusr,"system")
                .set(FiTask::getIndividualTag,individualTag)
                .update();
        return new Ai94ResVo("200","ok");
    }


    private String getUrlFileName(String url)
    {
        if(JPubUtils.IsEmpty(url)) return "";

        String[] arr=url.split("/");
        return arr[arr.length-1].trim();
    }
    private PlAi94Callbackmsg to9AI(Date currentDate,String uuid,JSONObject resp){

        String isndcs="0";// 是否ndcs数据

        String caseid=resp.getString("tag"); //caseid
        String[] split = caseid.split(",");
        String obId=split[0];
        String taskId=split[1];

        ObCallCase dbCallCaseDetail = getObCallCaseDetail(Long.valueOf(obId));
        if(dbCallCaseDetail==null){
            isndcs="1";
        }else {  //0
            FiTask dbTask = fiTaskService.getById(taskId);//如果ob校验通过再验证task表 ,同时通过证明是ndcs数据
            if(dbTask==null){
                isndcs="1";
            }
        }

        log.info("isndcs:{}",isndcs);

        PlAi94Callbackmsg ai94Callbackmsg=new PlAi94Callbackmsg();
        ai94Callbackmsg.setCallbackId(uuid);
        ai94Callbackmsg.setIsndcs(isndcs);
        ai94Callbackmsg.setUf1(obId);
        ai94Callbackmsg.setUf2(taskId);
        ai94Callbackmsg.setOptStatus("00");//状态：00-初始状态，01-已同步回盘表
//        ai94Callbackmsg.setCreateDate(DateUtil.date2String(new Date(), DateUtil.DATE_FORMAT_2));
        ai94Callbackmsg.setSyncUpdateTime(new Date());
        ai94Callbackmsg.setMsgtext(resp.toString());
        //lineType | HungupType    channelTag  gateway  status 文档没有对应字段但是返回里面有
        ai94Callbackmsg.setNumberId(resp.getString("id"));
        ai94Callbackmsg.setNumberMd5(resp.getString("numberMD5"));
        ai94Callbackmsg.setTransferStatus(resp.getString("transferStatus"));
        ai94Callbackmsg.setKeywords(resp.getString("keywords"));
        ai94Callbackmsg.setAnswerTime(resp.getString("answerTime"));
        ai94Callbackmsg.setSipCode(resp.getString("sipCode"));
        ai94Callbackmsg.setAnswerRecall(resp.getString("answerRecall"));
        ai94Callbackmsg.setHangupType(resp.getString("hangupType"));
        ai94Callbackmsg.setTemplateId(resp.getString("templateId"));
        ai94Callbackmsg.setAgentSpeakingDuration(resp.getString("agentSpeakingDuration"));
        ai94Callbackmsg.setIndividualTag(resp.getString("individualTag"));
        ai94Callbackmsg.setBatchId(resp.getString("batchId"));
        ai94Callbackmsg.setChatRecord(resp.getString("chatRecord"));
        ai94Callbackmsg.setCallType(resp.getString("callType"));
        ai94Callbackmsg.setAgentSpeakingTime(resp.getString("agentSpeakingTime"));
        ai94Callbackmsg.setNumber(resp.getString("number"));
        ai94Callbackmsg.setHangupType(resp.getString("HungupType"));//挂机方式
        ai94Callbackmsg.setSms(resp.getString("sms"));
        ai94Callbackmsg.setHangupTime(resp.getString("hangupTime"));
        ai94Callbackmsg.setTag(resp.getString("tag"));
        ai94Callbackmsg.setIntentTag(resp.getString("intentTag"));
        ai94Callbackmsg.setCallId(resp.getString("callId"));
        ai94Callbackmsg.setRingTime(resp.getString("ringTime"));
        ai94Callbackmsg.setAddWx(resp.getString("addWx"));
        ai94Callbackmsg.setTransferStatusCode(resp.getString("transferStatusCode"));
        ai94Callbackmsg.setBill(resp.getString("bill"));
        ai94Callbackmsg.setCallBeginTime(resp.getString("callBeginTime"));
        ai94Callbackmsg.setSpeakingTime(resp.getString("speakingTime"));
        ai94Callbackmsg.setSpeakingDuration(resp.getString("speakingDuration"));
        ai94Callbackmsg.setIntentDescription(resp.getString("intentDescription"));
        ai94Callbackmsg.setStatusDescription(resp.getString("statusDescription"));
        ai94Callbackmsg.setCompanyId(resp.getString("companyId"));
        ai94Callbackmsg.setTemplateName(resp.getString("templateName"));
        ai94Callbackmsg.setSpeakingTurns(resp.getString("speakingTurns"));
        ai94Callbackmsg.setTaskName(resp.getString("taskName"));
        ai94Callbackmsg.setTaskId(resp.getString("taskId"));
        ai94Callbackmsg.setImportTime(resp.getString("importTime"));
        ai94Callbackmsg.setProperties(resp.getString("properties"));
        ai94Callbackmsg.setStatusCode(resp.getString("statusCode"));
        PlAi94Callbackmsg byId = plAi94CallbackmsgService.getById(uuid);
        if(byId==null){
            ai94Callbackmsg.setSyncCreateTime(new Date());
        }
        boolean save = plAi94CallbackmsgService.saveOrUpdate(ai94Callbackmsg);
        JSONArray chatlist=resp.getJSONArray("chats");
        if(chatlist!=null && chatlist.size()!=0) {
            List<PlAi94Chat>ai94ChatList=new ArrayList<>();
            for (int i = 0; i < chatlist.size(); i++) {
                PlAi94Chat ai94Chat=new PlAi94Chat();
                JSONObject chat = chatlist.getJSONObject(i);
                ai94Chat.setSyncCreateTime(currentDate);
                ai94Chat.setSyncUpdateTime(currentDate);

                ai94Chat.setChatId(UUID.randomUUID().toString());
                ai94Chat.setCallbackId(uuid);
                ai94Chat.setFromNumber(chat.getString("fromNumber"));
                ai94Chat.setContent(chat.getString("content"));
                ai94Chat.setCreateTime(chat.getString("createTime"));
                ai94Chat.setChatName(chat.getString("chatName"));
                ai94Chat.setCallId(ai94Callbackmsg.getCallId());
                ai94ChatList.add(ai94Chat);
            }
            plAi94ChatService.saveBatch(ai94ChatList);
            ai94ChatList.clear();
        }
        return ai94Callbackmsg;
    }


    @Override
    public IPage<BatchAiCallResVo> aiCallSendBatchPage(BatchAiCallReqVo paras) {
        return baseMapper.aiCallSendBatchPage(new Page<>(paras.getPageNum(),paras.getPageSize()),paras);
    }

    @Override
    public IPage<BatchDetailAiCallResVo> aiCallSendDetailPage(JSysUser user,BatchAiCallReqVo paras) {
        boolean hasSecuPhnPermit = JUsrPerm.hasPermission(user,"disstar.phone");

        IPage<BatchDetailAiCallResVo> aiCallResVoIPage = baseMapper.aiCallSendDetailPage(new Page<>(paras.getPageNum(), paras.getPageSize()), paras)
                .convert(x -> {
                    //手机号加密
                    if(!hasSecuPhnPermit)
                    {
                        if(JPubUtils.IsNotEmpty(x.getPhone()) && x.getPhone().length() > 6 ){
                            String phn = x.getPhone().substring(0,3) + "***" + x.getPhone().substring(x.getPhone().length() -3);
                            x.setPhone(phn);
                        }
                    }
                    return x;
                });
        return aiCallResVoIPage;
    }

    private String toPdCCC(Integer code)
    {
        switch(code){
            case 1: return "CONNECT";
            case 2: return "POWEROFF";
            case 3: return "VACANT";
            case 4: return "VACANT";
            case 5: return "OUTSERVICE";
            case 6: return "BUSY";
            case 7: return "REJECT";
            case 8: return "OUTORDER";
            case 9: return "NOANSWER";
            case 10: return "BUSY";
            case 40: return "CALLDIST";
            default: return "NORMAL";
        }
    }
}




